#include <vector>

using std::vector;

class Solution {
public:
    int totalNQueens(int n) {
        vector<vector<int>> data;
        for (int i = 0; i < n; i++) {
            vector<int> tmp(n, 0);
            data.push_back(tmp);
        }
        int ret = 0;
        dfs(data, 0, n, ret);
        return ret;
    }

    void dfs(vector<vector<int>>& data, int row, int n, int& ret) {
        if (row == n) {
            ret++;
        }
        else {
            for (int col = 0; col < n; col++) {
                if (is_valid(data, row, col)) {
                    data[row][col] = 1;
                    dfs(data, row + 1, n, ret);
                    data[row][col] = 0;
                }
            }
        }
    }

    bool is_valid(vector<vector<int>>& data, int row, int col) {
        for (int i = 0; i < row; i++) {
            if (data[i][col] == 1) {
                return false;
            }
        }
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
            if (data[i][j] == 1) {
                return false;
            }
        }
        for (int i = row - 1, j = col + 1; i >= 0 && j < data.size(); i--, j++) {
            if (data[i][j] == 1) {
                return false;
            }
        }
        return true;
    }
};